<template>
    <div class="task-editor">
      <TopBar />
      <div class="step-nav-center">
        <StepNav :currentStep="currentStep" :steps="steps" @stepClick="handleStepClick" />
      </div>
      <div class="task-editor-content">
        <Step1Basic ref="step1Ref" v-show="currentStep === 1" v-model="step1Data.value" />
        <Step2RuleConfig ref="step2Ref" v-show="currentStep === 2" v-model="step2Data" />
        <Step3NotifyConfig v-show="currentStep === 3" v-model="step3Data" />
      </div>
      <BottomBar
        :currentStep="currentStep"
        :canNext="canNext"
        :canPrev="canPrev"
        @next="nextStep"
        @prev="prevStep"
        @finish="finish"
        @cancel="handleCancel"
      />
      <el-dialog v-model="showParamsDialog" title="接口入参预览" width="600px">
        <el-input type="textarea" :rows="18" v-model="paramsPreview" readonly style="font-family: monospace;" />
        <pre style="background:#f7f7f7;max-height:300px;overflow:auto;font-size:13px;">{{ paramsPreview }}</pre>
        <template #footer>
          <el-button type="default" @click="showParamsDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSend">确认并提交</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onBeforeUnmount, reactive, nextTick } from 'vue'
  import { useRouter } from 'vue-router'
  import TopBar from '../components/TaskFlow/TopBar.vue'
  import StepNav from '../components/TaskFlow/StepNav.vue'
  import BottomBar from '../components/TaskFlow/BottomBar.vue'
  import Step1Basic from '../components/TaskFlow/Step1Basic.vue'
  import Step2RuleConfig from '../components/TaskFlow/Step2RuleConfig.vue'
  import Step3NotifyConfig from '../components/TaskFlow/Step3NotifyConfig.vue'
  import { ElMessage } from 'element-plus'
  
  const router = useRouter()
  
  const steps = [
    { title: '任务基本信息' },
    { title: '规则配置' },
    { title: '通知规则配置' }
  ]
  const currentStep = ref(1)
  
  const canPrev = computed(() => currentStep.value > 1)
  const canNext = computed(() => currentStep.value < 3)
  
  // 三步数据提升到父组件
  const step1Data = ref({
    taskTitle: '',
    taskSubtitle: '',
    taskDescription: '',
    taskType: '',
    taskCoverUrl: '',
    startTime: '',
    endTime: '',
    claimType: 'once',
    userGroupType: 'all',
    showPos: [],
    priority: 50,
    maxParticipate: 0,
    limitTime: 0
  })
  const step2Data = reactive([])
  const step3Data = reactive({
    notifyTrigger: {
      complete: true,
      expire: false,
      expireAdvance: 2,
      reward: false
    },
    channels: {
      inbox: {
        enable: true,
        title: '',
        content: '',
        link: '',
        sendTime: 'immediate',
        delay: 10
      },
      sms: {
        enable: false,
        templateCode: ''
      },
      popup: {
        enable: false,
        title: '',
        content: '',
        style: 'simple',
        times: 0,
        position: 'center'
      },
      email: {
        enable: false,
        subject: '',
        content: '',
        attachments: [],
        sendTime: 'immediate',
        delay: 10
      }
    },
    advanced: {
      frequency: 0,
      group: 'all'
    }
  })
  
  const showParamsDialog = ref(false)
  const paramsPreview = ref('')
  let paramsCache = null
  let sending = false // 防止多次提交
  const step2Ref = ref(null)
  const step1Ref = ref(null)
  
  function nextStep() {
    if (currentStep.value === 1 && step1Ref.value) {
      step1Ref.value.saveToLocalStorage()
    }
    if (currentStep.value === 1) {
      const step1 = JSON.parse(localStorage.getItem('step1Data') || '{}')
      if (!step1.taskTitle || !step1.taskType) {
        ElMessage.warning('请填写任务标题和任务类型！')
        return
      }
    }
    if (currentStep.value === 2) {
      const step2 = JSON.parse(localStorage.getItem('step2Data') || '[]')
      if (!Array.isArray(step2) || step2.length === 0) {
        ElMessage.warning('请至少配置一个任务规则！')
        return
      }
      for (const rule of step2) {
        if (!rule.benefits || !rule.benefits[0] || !rule.benefits[0].rewardType) {
          ElMessage.warning('每条任务规则的奖励类型为必选项！')
          return
        }
      }
    }
    if (currentStep.value < 3) currentStep.value++
  }
  function prevStep() {
    if (currentStep.value === 2 && step1Ref.value) {
      step1Ref.value.saveToLocalStorage()
    }
    if (currentStep.value > 1) currentStep.value--
  }
  function handleStepClick(step) {
    if (currentStep.value === 1 && step1Ref.value) {
      step1Ref.value.saveToLocalStorage()
    }
    if (step === 2 && currentStep.value === 1) {
      const step1 = JSON.parse(localStorage.getItem('step1Data') || '{}')
      if (!step1.taskTitle || !step1.taskType) {
        ElMessage.warning('请填写任务标题和任务类型！')
        return
      }
    }
    if (step === 3 && currentStep.value <= 2) {
      const step2 = JSON.parse(localStorage.getItem('step2Data') || '[]')
      if (!Array.isArray(step2) || step2.length === 0) {
        ElMessage.warning('请至少配置一个任务规则！')
        return
      }
      for (const rule of step2) {
        if (!rule.benefits || !rule.benefits[0] || !rule.benefits[0].rewardType) {
          ElMessage.warning('每条任务规则的奖励类型为必选项！')
          return
        }
      }
    }
    if (step <= currentStep.value + 1) currentStep.value = step
  }
  function finish() {
    nextTick(() => {
      const step1Data = JSON.parse(localStorage.getItem('step1Data') || '{}')
      const step2Data = JSON.parse(localStorage.getItem('step2Data') || '[]')
      const step3Data = JSON.parse(localStorage.getItem('step3Data') || '{}')
      if (!step1Data.taskTitle || !step1Data.taskType) {
        ElMessage.warning('请填写任务标题和任务类型！')
        return
      }
      if (!Array.isArray(step2Data) || step2Data.length === 0) {
        ElMessage.warning('请至少配置一个任务规则！')
        return
      }
      for (const rule of step2Data) {
        if (!rule.benefits || !rule.benefits[0] || !rule.benefits[0].rewardType) {
          ElMessage.warning('每条任务规则的奖励类型为必选项！')
          return
        }
      }
      const params = {
        taskDTO: {
          taskInfo: step1Data,
          taskRule: step2Data,
          taskNotification: step3Data
        }
      }
      paramsPreview.value = JSON.stringify(params, null, 2)
      paramsCache = params
      showParamsDialog.value = true
    })
  }
  async function confirmSend() {
    if (sending) return
    sending = true
    showParamsDialog.value = false
    try {
      const res = await fetch('/api/task', {
        method: 'POST',
        headers: { 
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(paramsCache)
      })
      const data = await res.json()
      if (data && data.success) {
        ElMessage.success('任务创建成功！')
        localStorage.removeItem('step1Data')
        localStorage.removeItem('step2Data')
        localStorage.removeItem('step3Data')
        router.push({ path: '/home', query: { menu: 'task-list' } })
      } else {
        ElMessage.error('任务创建失败！' + (data && data.errMessage ? ('\n' + data.errMessage) : ''))
      }
    } catch (e) {
      ElMessage.error('接口请求失败！')
    } finally {
      sending = false
    }
  }
  function handleCancel() {
    router.push({ path: '/home', query: { menu: 'task-list' } })
  }
  
  onBeforeUnmount(() => {
    // 离开页面时清除所有缓存数据
    localStorage.removeItem('step1Data')
    localStorage.removeItem('step2Data')
    localStorage.removeItem('step3Data')
    
    // 清空组件内部数据
    for (const k in step1Data.value) step1Data.value[k] = ''
    step1Data.value.showPos = []
    step1Data.value.priority = 50
    step1Data.value.cycle = 'once'
    step1Data.value.userGroup = 'all'
    if (Array.isArray(step2Data)) step2Data.length = 0
    for (const k in step3Data) step3Data[k] = ''
    currentStep.value = 1
  })
  </script>
  
  <style scoped>
  .task-editor {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  .step-nav-center {
    display: flex;
    justify-content: center;
    margin-top: 12px;
    margin-bottom: 12px;
  }
  .task-editor-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 24px;
    background: #f7f8fa;
  }
  </style>